﻿/******************************************************************
 ** 文件名:
 ** Copyright (c) 2017-2018 汉威公司技术研究院
 ** 创建人:成涛
 ** 日 期:2017-06-12.
 ** 修改人:成涛
 ** 日 期:2018-04-03  修改了文件上传部分,关于文件的操作都添加了dirMark参数
 ** 描 述:数据访问服务js版sdk 解决了跨域及低版本浏览器ajax请求的的问题
 ** 版 本:1.20180403
 ******************************************************************/

var hostsurl = "192.168.1.183:8050";
// var token = "7AFF180DD19D71A682C91C1C46F32DBF4BB5C614A4DB3EEF0A457606DE78442F299282C85DC090CC";
// var token = '3AB1AC53683EF67F3412144288D6F32F38CCC6284D41A9A3A01D294307C5C36C7DFCCC3DB8CF76DD3FFDF72F94472C074081008B6F1D2D2833BA0A77796E1F67C3FF42882266D8E3';
var token;
var callCode = "jhepbppt";
var system = "xx";
var module = "xx";
window.hwDas = {
        token: "", //认证token
        ecyLogin: "", //加密用户名
        hosts: [], //服务器ip及端口列表
        appinfo: {
            callCode: "",
            module: "",
            system: ""
        },
        acceptType: {
            '*': 'text/javascript, text/html, application/xml, text/xml, */*',
            'xml': 'application/xml, text/xml',
            'html': 'text/html',
            'text': 'text/plain',
            'json': 'application/json, text/javascript',
            'js': 'application/javascript, text/javascript'

        },
        corsSup: ""
    }
    /*
    方法功能:登录
    参数说明:
    login:登录名
    password:密码
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.login = function(login, password, successback, errorback) {
        function successfunc(res) {
            if (res.isSucceed) {
                hwDas.token = res.token;
                hwDas.setCookie("hwToken", hwDas.token, { path: "/" });
            }
            if (typeof(successback) === "function") {
                successback(res);
            }
        }
        if (login === "") {
            throw new Error("第一个参数不能为空,请检查");
        }
        if (password === "") {
            throw new Error("第二个参数不能为空,请检查");
        }
        hwDas.call("get", { url: "login", type: "ssodas" }, {}, { login: login, password: password }, {}, successfunc, errorback);
    }
    /*
    方法功能:单点登录
    参数说明:
    id:应用id
    backurl:单点页面url
    */
hwDas.signin = function(id, backurl) {
        hwDas.call("get", { url: "signin", type: "ssodas" }, {}, { id: id, backurl: backurl }, {});
    }
    /*
    方法功能:注销
    参数说明:无
    */
hwDas.logout = function() {
        var token = hwDas.token || hwDas.getCookie("hwToken");
        hwDas.call("get", { url: "logout", type: "ssodas" }, {}, { token: token }, {});
    }
    /*
    方法功能:认证,验证token
    参数说明:
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.auth = function(successback, errorback) {
        var token = hwDas.token || hwDas.getCookie("hwToken");
        var ecyLogin = hwDas.ecyLogin || hwDas.getCookie("EcyLogin");
        hwDas.call("get", { url: "auth", type: "ssodas" }, {}, {}, { token: token, ecyLogin: ecyLogin }, successback, errorback);
    }
    /*
    方法功能:获取数据
    参数说明:
    parturl:相对Url地址
    headers:请求头,格式为{}对象  如果分页要设置:startIndex: 记录开始索引, pageSize: 获取数据量
    params:请求参数,格式为{}对象
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.get = function(parturl, headers, params, successback, errorback) {
        hwDas.call("get", { url: parturl, type: "idedas" }, headers, params, {}, successback, errorback);
    }
    /*
    方法功能:添加数据
    参数说明:
    parturl:相对Url地址
    headers:请求头,格式为{}对象
    params:请求参数,格式为{}对象
    datas:请求内容,格式为[{},{}]数组对象(多条记录)或是{}对象(单条记录)
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.add = function(parturl, headers, params, datas, successback, errorback) {
        if (typeof(datas) === "function" || typeof(datas) === "string") {
            throw new Error("调用add方法时,第四个参数类型有误,请检查");
        }
        var bodydata = hwDas.getbody(datas);
        hwDas.call("post", { url: parturl, type: "idedas" }, headers, params, bodydata, successback, errorback);
    }
    /*
    方法功能:修改数据
    参数说明:
    parturl:相对Url地址
    headers:请求头,格式为{}对象
    params:请求参数,格式为{}对象
    datas:请求内容,格式为[{},{}]数组对象(多条记录)或是{}对象(单条记录)
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.edit = function(parturl, headers, params, datas, successback, errorback) {
        if (typeof(datas) === "function" || typeof(datas) === "string") {
            throw new Error("调用edit方法时,第四个参数类型有误,请检查");
        }
        var bodydata = hwDas.getbody(datas);
        hwDas.call("put", { url: parturl, type: "idedas" }, headers, params, bodydata, successback, errorback);
    }
    /*
    方法功能:删除数据
    参数说明:
    parturl:相对Url地址
    headers:请求头,格式为{}对象
    params:请求参数,格式为{}对象
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.del = function(parturl, headers, params, successback, errorback) {
        hwDas.call("delete", { url: parturl, type: "idedas" }, headers, params, {}, successback, errorback);
    }
    /*
    方法功能:保存数据(保存数据集)
    参数说明:
    parturl:相对Url地址
    headers:请求头,格式为{}对象
    params:请求参数,格式为{}对象
    datas:请求内容,格式为[{Value:{},Original:{},RowState:insert},{...}]数组对象(多条记录)或是{...}对象(单条记录)
    --其中Value表示新值,RowState表示行状态(insert、update、delete),Original表示修改前的值（新增状态不需要传递）
    --Original中的值 在服务变量中用:字段名_org的形式表示, 程序默认根据该规则把数据转换成变量值
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.save = function(parturl, headers, params, datas, successback, errorback) {
        if (typeof(datas) === "function" || typeof(datas) === "string") {
            throw new Error("调用save方法时,第四个参数类型有误,请检查");
        }

        var bodydata = hwDas.getbody(datas);
        hwDas.call("save", { url: parturl, type: "idedas" }, headers, params, bodydata, successback, errorback);
    }
    /*
    方法功能:检测文件是否存在
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    filePath:文件的相对存储路径
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.exist = function(dirMark, filePath, successback, errorback) {
        var headers = { FilePath: filePath };
        hwDas.call("get", { url: "FileService/" + dirMark + "/Exist", type: "orddas" }, headers, {}, {}, successback, errorback);
    }
    /*
    方法功能:读取文件内容成字符串格式
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    filePath:文件的相对存储路径
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.read = function(dirMark, filePath, successback, errorback) {
        var headers = { FilePath: filePath };
        hwDas.call("get", { url: "FileService/" + dirMark + "/Read", type: "orddas" }, headers, {}, {}, successback, errorback);
    }
    /*
    方法功能:把字符串内容存储成文件
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    filePath:文件的相对存储路径
    fileContent:文件内容,字符串格式
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.write = function(dirMark, filePath, fileContent, successback, errorback) {
        var headers = { FilePath: filePath };
        hwDas.call("post", { url: "FileService/" + dirMark + "/Write", type: "orddas" }, headers, {}, fileContent, successback, errorback);
    }
    /*
    方法功能:删除文件
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    filePath:要删除文件的相对路径
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.remove = function(dirMark, filePath, successback, errorback) {
        var headers = { FilePath: filePath };
        hwDas.call("post", { url: "FileService/" + dirMark + "/Delete", type: "orddas" }, headers, {}, {}, successback, errorback);
    }
    /*
    方法功能:拷贝文件
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    filePath:源相对目录
    destPath:目标相对目录
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.copy = function(dirMark, filePath, destPath, successback, errorback) {
        var headers = { FilePath: filePath, DestPath: destPath };
        hwDas.call("post", { url: "FileService/" + dirMark + "/Copy", type: "orddas" }, headers, {}, {}, successback, errorback);
    }
    /*
    方法功能:移动文件
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    filePath:源相对目录
    destPath:目标相对目录
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.move = function(dirMark, filePath, destPath, successback, errorback) {
        var headers = { FilePath: filePath, DestPath: destPath };
        hwDas.call("post", { url: "FileService/" + dirMark + "/Move", type: "orddas" }, headers, {}, {}, successback, errorback);
    }
    /*
    方法功能:获取指定目录下的文件列表
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    filePath:相对目录
    fileType: 参数包括:fileType 文件后缀格式例如:".doc"
    successback:成功回调函数
    errorback:错误回调函数
    */
hwDas.getdirs = function(dirMark, filePath, fileType, successback, errorback) {
        var headers = { FilePath: filePath };
        if (Object.prototype.toString.call(fileType) == '[object Array]') {
            headers.FileType = fileType.join(",");
        } else {
            headers.FileType = fileType;
        }
        hwDas.call("get", { url: "FileService/" + dirMark + "/Dir", type: "orddas" }, headers, {}, {}, successback, errorback);
    }
    /*
    方法功能:下载文件
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    filePath:下载文件相对路径
    destName:下载文件时用户下载页面文件名称
    */
hwDas.down = function(dirMark, filePath, destName) {
        var url = hwDas.geturl({ url: "FileService/" + dirMark + "/Down?FilePath=" + encodeURIComponent(filePath) + "&destName=" + encodeURIComponent(destName), type: "orddas" });
        window.open(url, "_self");
    }
    /*
    方法功能:获取上传url
    参数说明:
    dirMark:路径标识,格式为字符串,服务管理人员获取,其中vmd2.0使用的是vmd
    dirPath:保存相对目录,可为空
    */
hwDas.getuploadurl = function(dirMark, dirPath) {
        if (dirPath === undefined) {
            dirPath = "";
        }
        return hwDas.geturl({ url: "FileService/" + dirMark + "/Upload?dirPath=" + encodeURIComponent(dirPath), type: "orddas" });
    }
    // 转换数据
hwDas.getbody = function(data) {
        var paramsList = [];
        if (data && data != null) {
            if (Object.prototype.toString.call(data) == '[object Array]') {
                paramsList = data;
            } else {
                paramsList.push(data);
            }
        } else {
            paramsList.push({});
        }
        return paramsList;
    }
    //参数转换
hwDas.call = function(requestType, urlconfig, headers, params, datas, successback, errorback) {
        var config = {}; //如果是数据访问服务就得填写,如果不是定制的数据服务就填写idedas为false
        if (typeof urlconfig === "object") {
            config = urlconfig;
        } else {
            config.url = urlconfig;
        }
        if (headers.idedas === false) {
            config.type = "orddas";
            delete headers.idedas;
        } else {
            config.type = config.type || "idedas";
        }
        hwDas.ajax({
            urlconfig: config,
            type: requestType,
            headers: headers,
            params: params,
            data: datas,
            success: successback,
            error: errorback
        });
    }
    //成功后返回路径
hwDas.geturl = function(pathname) {
        var config = {};
        if (typeof pathname === "object") {
            config = pathname;
            pathname = config.url;
        } else {
            config.type = "orddas";
            config.url = pathname;
        }
        if (pathname.trim().indexOf("http://") == 0) {
            return pathname;
        }
        var hostcount = hwDas.hosts.length;
        var host_i = Math.round(Math.random() * (hostcount - 1)); //可基本均衡获取0到hostcount的随机整数
        var pathurl = (pathname.substring(0, 1) == '/') ? pathname.substring(1) : pathname;
        var allurl = "";
        if (hostcount > 0) {
            if (config.type == "ssodas") {
                allurl = "http://" + hwDas.hosts[host_i] + "/SSOService" + "/" + pathurl;
            } else if (config.type == "idedas") {
                allurl = "http://" + hwDas.hosts[host_i] + "/DasService/DataService" + "/" + pathurl;
            } else {
                allurl = "http://" + hwDas.hosts[host_i] + "/DasService" + "/" + pathurl;
            }
        } else {
            allurl = "../" + pathurl;
        }

        // 测试用
        //if (config.type == "idedas") {
        //     allurl = "http://" + hwDas.hosts[host_i] + "/DataService/" + pathurl;
        // }
        //else {
        // allurl = "http://" + hwDas.hosts[host_i] + "/" + pathurl;
        // }

        return allurl;
    }
    //重新过滤参数
hwDas.rehandle = function(options) {
        var headers = options.headers;
        var datas = options.data;
        if (options.urlconfig.type == "idedas") {
            datas = hwDas.getbody(options.data);
        }
        var token = hwDas.token || hwDas.getCookie("hwToken") || hwDas.getUrlParameter("hwToken");
        var dasheaders = {
            CallCode: hwDas.appinfo.callCode,
            SystemID: hwDas.appinfo.system,
            ModuleID: hwDas.appinfo.module,
        }
        if (token) {
            dasheaders.Token = token;
        } else {
            var ecyLogin = hwDas.ecyLogin || hwDas.getCookie("EcyLogin") || hwDas.getUrlParameter("EcyLogin");
            if (ecyLogin) {
                dasheaders.EcyLogin = ecyLogin;
            }
        }

        if (headers) {
            if (dasheaders.EcyLogin || dasheaders.token) { //如果已经赋值,则删除自定义传递的 
                delete headers.Ecylogin;
                delete headers.token;
            }
            hwDas.extend(dasheaders, headers);
        }
        return {
            url: hwDas.geturl(options.urlconfig),
            type: options.type,
            async: options.async,
            timeout: options.timeout,
            data: datas,
            params: options.params,
            headers: dasheaders,
            contentType: options.contentType == undefined ? "application/json; charset=UTF-8" : options.contentType,
            dataType: options.dataType,
            success: function(resultdata, status) {
                if (resultdata.isSucceed != false && typeof(options.success) == "function") {
                    options.success(resultdata, status);
                } else {
                    if (typeof(options.error) == "function") {
                        options.error(resultdata.errMsg, status);
                    } else {
                        alert(resultdata.errMsg);
                    }
                }
            },
            error: options.error,
            complete: options.complete,
            progress: options.progress
        };
    }
    //创建请求对象
hwDas.httpRequest = function() {
        var xdr;
        if (window.XMLHttpRequest) {
            xdr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            xdr = new ActiveXObject("Microsoft.XmlHttp");
        } else {
            throw "不支持http请求";
        }
        return xdr;
    }
    //判断是否要跨域处理
hwDas.crossSupport = function() {
        if (hwDas.corsSup == "") {
            var browser = navigator.appName
            hwDas.corsSup = true;
            if (browser == "Microsoft Internet Explorer") {
                var b_version = navigator.appVersion
                var version = b_version.split(";");
                var trim_Version = version[1].replace(/[ ]/g, "");
                if (trim_Version == "MSIE6.0") {
                    hwDas.corsSup = false;
                } else if (trim_Version == "MSIE7.0") {
                    hwDas.corsSup = false;
                } else if (trim_Version == "MSIE8.0") {
                    hwDas.corsSup = false;
                } else if (trim_Version == "MSIE9.0") {
                    hwDas.corsSup = false;
                }
            }
        }
        return hwDas.corsSup;
    }
    //发送请求
hwDas.ajax = function(options) {
        if (options.das) //兼容处理
        {
            if (options.das.idedas === true) {
                options.das.type = "idedas";
            } else {
                options.das.type = "orddas";
            }
        }
        options.urlconfig = options.urlconfig || options.das;
        delete options.das;
        if (options.urlconfig) {
            options.urlconfig.url = options.urlconfig.url || options.url;
            options = hwDas.rehandle(options);
        }

        options.dataType = options.dataType == undefined ? "json" : options.dataType;
        options.async = options.async == undefined ? true : options.async;
        options.type = options.type.toLowerCase();
        options.timeout = /^\d+$/.test(options.timeout) ? options.timeout : 20 * 1000; //默认20秒超时
        var httpRegEx = /^(https?:)?\/\//i;
        var getOrPostRegEx = /^get|post$/i;
        var sameSchemeRegEx = new RegExp('^(\/\/|' + location.protocol + ')', 'i');
        var isXDomain = false;
        if ((!hwDas.crossSupport()) && window.XDomainRequest) {
            if (options.async && getOrPostRegEx.test(options.type) && httpRegEx.test(options.url) && sameSchemeRegEx.test(options.url)) {
                isXDomain = true;
            }
        }
        if (!options.headers) {
            options.headers = {};
        }
        var type = options.type;
        if (type == "save") {
            options.type = "post";
            options.headers.ActionType = type;
        } else {
            if (options.type != "post" && options.type != "get" && isXDomain) {
                options.type = "post";
                options.headers.ActionType = type;
            }
        }
        var state = 1;
        if (isXDomain) {
            hwDas.sendXDomain(options, done);
        } else {
            hwDas.sendXMLHttp(options, done);
        }

        function done(xdr, status, response) {
            var isSuccess;
            if (state === 2) {
                return;
            }
            state = 2;
            isSuccess = status >= 200 && status < 300 || status == 304;
            if (isSuccess) {
                if (status === 204) {
                    response.error = "nocontent";
                } else if (status === 304) {
                    response.error = "notmodified";
                }
            } else {
                if (status && status < 0) {
                    status = 0;
                } else if (status == 401) {
                    response.error = "Token认证失败";
                } else if (!response.error) {
                    response.error = "系统异常，请稍后重试！";
                }
            }
            if (isSuccess) {
                if (options.success && typeof(options.success) == "function") {
                    options.success(response.data, status);
                }
            } else {
                if (options.error && typeof(options.error) == "function") {
                    options.error(response.error, status);
                } else {
                    alert(response.error);
                }
            }
            if (options.complete && typeof(options.complete) == "function") {
                options.complete(xdr, status);
            }
        }
    }
    //ie10+, Chrome, Firefox, Opera 8.0+, Safari
hwDas.sendXMLHttp = function(options, complete) {
        var xdr = hwDas.httpRequest();
        //xdr.timeout = options.timeout;
        var timeout = false;
        var timer = setTimeout(function() {
            timeout = true;
            xdr.abort(); //请求中止
        }, options.timeout);
        var isQt = (navigator.userAgent.match(/AppleWebKit/) != null && navigator.userAgent.match(/Qt/) != null && navigator.userAgent.match(/Safari/) != null);
        //onreadystatechange函数对象
        xdr.onreadystatechange = function() {
            //readyState 的值等于4，从服务器拿到了数据
            if (xdr.readyState == 4 || (isQt == true && xdr.readyState == 3)) {
                clearTimeout(timer); //取消等待的超时
                hwDas.acceptResult(xdr, xdr.status, options.dataType, complete); //回调服务器响应数据
            }
            if (timeout) return; //忽略中止请求
        }
        var params = {};
        if (options.params) {
            hwDas.extend(params, options.params);
        }
        params.hwdhxrad = hwDas.getRadStr();
        var paramstr = hwDas.param2Str(params);
        //如果url参数超长就转成用post传输
        if (paramstr.length > 2000 && (options.type == "get" || options.type == "delete")) {
            options.headers.ActionType = options.type;
            options.type = "post";
            options.data = [];
            options.data.push(options.params);
            options.params = {};
            params.hwdhxrad = hwDas.getRadStr();
            paramstr = hwDas.param2Str(params);
        }
        var url = options.url + (options.url.indexOf("?") < 0 ? "?" : "&") + paramstr;

        xdr.onerror = function() {
            complete(xdr, 500, xdr.responseText);
        }
        xdr.ontimeout = function() {
            complete(xdr, 500, { error: 'timeout' });
        }
        xdr.onprogress = function(e) {
                if (options.progress && typeof(options.error) == "function") {
                    options.progress(xdr, e);
                }
            }
            //初始化HTTP请求
        xdr.open(options.type, url, options.async);
        xdr.setRequestHeader("Accept", hwDas.acceptType[options.dataType]);
        if (options.headers && options.headers != null) {
            for (var header in options.headers)
                xdr.setRequestHeader(header, options.headers[header]);
        }
        xdr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        if (options.type === "post" || options.type === "put") {
            if (!options.contentType) {
                //若是post提交，则设置content-Type 为application/x-www-four-urlencoded
                options.contentType = "application/x-www-form-urlencoded;charset=UTF-8";
            }
        }
        if (options.contentType) {
            xdr.setRequestHeader("Content-type", options.contentType);
        }
        if (options.type == "post" || options.type == "put") {
            //给指定的HTTP请求头赋值
            var sendData = {};
            if (options.data) {
                if (typeof options.data === "string") {
                    sendData = options.data;
                } else {
                    sendData = JSON.stringify(options.data);
                }
            }
            xdr.send(sendData);
        } else {
            xdr.send();
        }
        if (!options.async) return xdr;
    }
    //跨域支持 ie9-
hwDas.sendXDomain = function(options, complete) {
        var xdr = new XDomainRequest();
        xdr.timeout = options.timeout;
        xdr.ontimeout = function() {
            complete(xdr, 500, { error: 'timeout' });
        }
        xdr.onprogress = function(e) {
            if (options.progress && typeof(options.error) == "function") {
                options.progress(xdr, e);
            }
        }
        xdr.onerror = function() {
                complete(xdr, 500, { error: xdr.responseText });
            }
            //onreadystatechange函数对象
        xdr.onload = function() {
            hwDas.acceptResult(xdr, 200, options.dataType, complete);
        }
        var params = { hwdhxrad: hwDas.getRadStr() };
        if (options.params) {
            hwDas.extend(params, options.params);
        }
        if (options.headers) {
            hwDas.extend(params, options.headers);
        }
        var paramstr = hwDas.param2Str(params);

        //如果url参数超长就转成用post传输
        if (paramstr.length > 2000 && (options.type == "get")) {
            options.headers.ActionType = options.type;
            options.type = "post";
            options.data = [];
            options.data.push(params);
            options.params = {};
            params.hwdhxrad = hwDas.getRadStr();
            paramstr = hwDas.param2Str(params);
        }
        var url = encodeURI(options.url) + (options.url.indexOf("?") < 0 ? "?" : "&") + paramstr;
        //初始化HTTP请求
        xdr.open(options.type, url);
        if (options.type == "post") {
            //给指定的HTTP请求头赋值
            var sendData = "";
            if (options.data) {
                if (typeof options.data === "string") {
                    sendData = options.data;
                } else {
                    sendData = JSON.stringify(options.data);
                }
            }
            xdr.send(sendData);
        } else {
            xdr.send();
        }
        if (!options.async) return xdr;
    }
    //处理返回值
hwDas.acceptResult = function(xdr, status, userType, complete) {
        try {
            var response = { error: "", data: "" }
            if (status >= 200 && status < 300 || status == 304) {
                if (xdr.responseText != "") {
                    if (userType === 'json' || (userType !== 'text' && /\/json/i.test(xdr.contentType))) {
                        try {
                            response.data = JSON.parse(xdr.responseText);
                        } catch (e) {
                            status = 500;
                            response.error = 'Could not parse JSON in response,' + e;
                        }
                    } else if (userType === 'xml' || (userType !== 'text' && /\/xml/i.test(xdr.contentType))) {
                        if (window.ActiveXObject) {
                            var doc = new ActiveXObject('Microsoft.XMLDOM');
                            doc.async = false;
                            try {
                                doc.loadXML(xdr.responseText);
                            } catch (e) {
                                doc = undefined;
                            }
                            if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
                                status = 500;
                                response.error = 'Could not parse Xml in response';
                            }
                            response.data = doc;
                        } else {
                            if (xdr.responseXML && xdr.responseXML.parseError && xdr.responseXML.parseError.errorCode && xdr.responseXML.parseError.reason) {
                                status = 500;
                                response.error = xdr.responseXML.parseError.reason;
                            } else if (xdr.responseXML) {
                                response.data = xdr.responseXML;
                            } else {
                                response.data = xdr.responseText;
                            }
                        }
                    } else if (userType === 'js') {
                        try {
                            response.data = eval(xdr.responseText);
                        } catch (e) {
                            status = 500;
                            response.error = 'parseerror';
                        }
                    } else {
                        response.data = xdr.responseText;
                    }
                }
            } else {
                response.error = xdr.responseText;
            }
        } catch (parseMessage) {
            throw parseMessage;
        } finally {
            complete(xdr, status, response);
        }
    }
    //对象合并
hwDas.extend = function(o, n) {
        for (var p in n) {
            if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p)))
                o[p] = n[p];
        }
    }
    //随机码
hwDas.getRadStr = function(len) {
        len = len || 5;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = $chars.length;
        var res = "";
        for (i = 0; i < len; i++) {
            res += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return res;
    }
    //对象转换成编码的字符串
hwDas.param2Str = function(urlParams) {
        var sendString = [];
        if (typeof urlParams === "string") {
            var tmpArr = String.prototype.split.call(urlParams, '&');
            for (var i = 0, j = tmpArr.length; i < j; i++) {
                var datum = tmpArr[i].split('=');
                sendString.push(encodeURIComponent(datum[0]) + "=" + encodeURIComponent(datum[1]));
            }
        } else if (typeof urlParams === 'object') {
            for (var k in urlParams) {
                var datum = urlParams[k];
                if (datum === undefined || datum == "" || datum == null) {
                    continue;
                }
                if (Object.prototype.toString.call(datum) == "[object Array]") {
                    for (var i = 0, j = datum.length; i < j; i++) {
                        sendString.push(encodeURIComponent(k) + "[]=" + encodeURIComponent(datum[i]));
                    }
                } else {
                    sendString.push(encodeURIComponent(k) + "=" + encodeURIComponent(datum));
                }
            }
        }
        return sendString.join('&');
    }
    //获取url参数
hwDas.getUrlParameter = function(param) {
        var reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
    //获取cookie值
hwDas.getCookie = function(cname) {
        var arr, reg = new RegExp("(^| )" + cname + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return decodeURIComponent(arr[2]);
        else
            return null;
    }
    //设置cookie值
hwDas.setCookie = function(key, value, options) {
        if (typeof options.expires === 'number') {
            var days = options.expires,
                t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '',
            options.path ? '; path=' + options.path : '; path=/',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));

    }
    //字符串去掉空格
if (!String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
    };
}
//json 兼容
if (typeof JSON !== "object") {
    JSON = {};
}
(function() {
    "use strict";
    var rx_one = /^[\],:{}\s]*$/;
    var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
    var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
    var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
    var rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;

    function f(n) {
        return n < 10 ? "0" + n : n;
    }

    function this_value() {
        return this.valueOf();
    }
    if (typeof Date.prototype.toJSON !== "function") {
        Date.prototype.toJSON = function() {
            return isFinite(this.valueOf()) ?
                this.getUTCFullYear() + "-" +
                f(this.getUTCMonth() + 1) + "-" +
                f(this.getUTCDate()) + "T" +
                f(this.getUTCHours()) + ":" +
                f(this.getUTCMinutes()) + ":" +
                f(this.getUTCSeconds()) + "Z" :
                null;
        };
        Boolean.prototype.toJSON = this_value;
        Number.prototype.toJSON = this_value;
        String.prototype.toJSON = this_value;
    }
    var gap;
    var indent;
    var meta;
    var rep;

    function quote(string) {
        rx_escapable.lastIndex = 0;
        return rx_escapable.test(string) ?
            "\"" + string.replace(rx_escapable, function(a) {
                var c = meta[a];
                return typeof c === "string" ?
                    c :
                    "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
            }) + "\"" :
            "\"" + string + "\"";
    }

    function str(key, holder) {
        var i; // The loop counter.
        var k; // The member key.
        var v; // The member value.
        var length;
        var mind = gap;
        var partial;
        var value = holder[key];
        if (value && typeof value === "object" &&
            typeof value.toJSON === "function") {
            value = value.toJSON(key);
        }
        if (typeof rep === "function") {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
            case "string":
                return quote(value);
            case "number":
                return isFinite(value) ?
                    String(value) :
                    "null";

            case "boolean":
            case "null":
                return String(value);
            case "object":
                if (!value) {
                    return "null";
                }
                gap += indent;
                partial = [];
                if (Object.prototype.toString.apply(value) === "[object Array]") {
                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || "null";
                    }
                    v = partial.length === 0 ?
                        "[]" :
                        gap ?
                        "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" :
                        "[" + partial.join(",") + "]";
                    gap = mind;
                    return v;
                }
                if (rep && typeof rep === "object") {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        if (typeof rep[i] === "string") {
                            k = rep[i];
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ": " : ":") + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ": " : ":") + v);
                            }
                        }
                    }
                }
                v = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}";
                gap = mind;
                return v;
        }
    }
    if (typeof JSON.stringify !== "function") {
        meta = { // table of character substitutions
            "\b": "\\b",
            "\t": "\\t",
            "\n": "\\n",
            "\f": "\\f",
            "\r": "\\r",
            "\"": "\\\"",
            "\\": "\\\\"
        };
        JSON.stringify = function(value, replacer, space) {
            var i;
            gap = "";
            indent = "";
            if (typeof space === "number") {
                for (i = 0; i < space; i += 1) {
                    indent += " ";
                }
            } else if (typeof space === "string") {
                indent = space;
            }
            rep = replacer;
            if (replacer && typeof replacer !== "function" &&
                (typeof replacer !== "object" ||
                    typeof replacer.length !== "number")) {
                throw new Error("JSON.stringify");
            }
            return str("", { "": value });
        }
    }

    if (typeof JSON.parse !== "function") {
        JSON.parse = function(text, reviver) {
            var j;

            function walk(holder, key) {
                var k;
                var v;
                var value = holder[key];
                if (value && typeof value === "object") {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }
            text = String(text);
            rx_dangerous.lastIndex = 0;
            if (rx_dangerous.test(text)) {
                text = text.replace(rx_dangerous, function(a) {
                    return "\\u" +
                        ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (
                rx_one.test(
                    text.replace(rx_two, "@").replace(rx_three, "]").replace(rx_four, "")
                )
            ) {
                j = eval("(" + text + ")");
                return (typeof reviver === "function") ? walk({ "": j }, "") : j;
            }
            throw new SyntaxError("JSON.parse");
        };
    }
}());